package com.market.fleamarket.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

    @Value("${file.upload-dir:uploads}")
    private String uploadDir;

    @PostConstruct
    public void init() {
        try {
            // 确保上传目录存在
            String uploadPath = System.getProperty("user.dir") + File.separator + uploadDir;
            Path directory = Paths.get(uploadPath);
            if (!Files.exists(directory)) {
                Files.createDirectories(directory);
                System.out.println("创建上传目录: " + uploadPath);
            } else {
                System.out.println("上传目录已存在: " + uploadPath);
            }
        } catch (IOException e) {
            System.err.println("初始化上传目录失败: " + e.getMessage());
        }
    }

    @PostMapping("/image")
    public ResponseEntity<?> uploadImage(@RequestParam("file") MultipartFile file, HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 检查用户是否登录
            if (session.getAttribute("user") == null) {
                response.put("error", "请先登录");
                return ResponseEntity.status(401).body(response);
            }

            // 检查文件是否为空
            if (file.isEmpty()) {
                response.put("error", "请选择一个文件");
                return ResponseEntity.badRequest().body(response);
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                response.put("error", "只允许上传图片文件");
                return ResponseEntity.badRequest().body(response);
            }

            // 创建上传目录
            String uploadPath = System.getProperty("user.dir") + File.separator + uploadDir;
            Path directory = Paths.get(uploadPath);
            if (!Files.exists(directory)) {
                Files.createDirectories(directory);
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename != null ?
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
            String filename = UUID.randomUUID().toString() + extension;

            // 保存文件
            Path filePath = Paths.get(uploadPath + File.separator + filename);
            Files.write(filePath, file.getBytes());

            // 返回图片URL - 修改为绝对路径，避免路径问题
            String contextPath = "";  // 可以从配置中获取上下文路径
            String imageUrl = contextPath + "/uploads/" + filename;

            // 打印调试信息
            System.out.println("文件上传成功: " + filePath.toAbsolutePath());
            System.out.println("生成的图片URL: " + imageUrl);

            response.put("imageUrl", imageUrl);
            response.put("absolutePath", filePath.toAbsolutePath().toString());

            return ResponseEntity.ok(response);
        } catch (IOException e) {
            response.put("error", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}